﻿using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections;
using System.Collections.Generic;
using Microsoft.SharePoint.Utilities;
using System.Web;

namespace AVO.Layouts.AVO
{
    public partial class avoeditfield : AVOPageBase
    {
        private Guid fid;

        protected FieldVisibilityConfig CurrentField;

        private ContentTypeConfiguration Configuration;

        public SPList CurrentList = SPContext.Current.List;
        public string ContentTypeName = null;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            string strctid = this.Request.QueryString["ctype"];
            var ctid = new SPContentTypeId(strctid);

            var cfg = this[ctid];
            ContentTypeName = cfg.ContentTypeName;
            Configuration = cfg;
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            string fieldId = this.Request.Params["fid"];

            fid = new Guid(fieldId);
            
            CurrentField = Configuration.FieldConfigurations.FirstOrDefault(f => f.FieldId.Equals(fid));

            if (!Page.IsPostBack)
            {
                chbEnabled.Checked = CurrentField.Enabled;
                tbScript.Text = CurrentField.ScriptFunction;
            }
        }

        protected void btnCheck_Clicked(object sender, EventArgs ea)
        {
            string script = tbScript.Text;
            //tbd
        }
        
        protected void btnSave_Clicked(object sender, EventArgs ea)
        {
            CurrentField.Enabled = chbEnabled.Checked;
            CurrentField.ScriptFunction = tbScript.Text;

            Configuration.Save();

            SPUtility.Redirect(PageToRedirectOnCancel, SPRedirectFlags.Default, this.Context);
        }

        public override string PageToRedirectOnCancel
        {
            get
            {
                return HttpUtility.UrlDecode(this.Request.QueryString["Source"]);
            }
        }
            
    }
}
